package apache;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;

public class Processor extends Thread {
	InputStream in;
	PrintStream out;
	static String WEB_ROOT = "E:\\tomcat6_8897\\webapps";

	public Processor(Socket socket) {
		try {
			InputStream in = socket.getInputStream();
			PrintStream out = new PrintStream(socket.getOutputStream());
			this.in = in;			
			this.out = out;
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void run() {
		String filename = parse(in);
		sendFileinfor(filename);
	}

	private String parse(InputStream in) {
		BufferedReader br = new BufferedReader(new InputStreamReader(in));
		String filename = null;
		try {
			String getmes = br.readLine();
			String[] mess = getmes.split(" ");
			if (mess == null || mess.length != 3) {
				sendErrorMessage("400", "query head is error");
				return null;
			}

			System.out.println("method=" + mess[0] + "||filename=" + mess[1]
					+ "||http version=" + mess[2]);
			filename = mess[1];
		} catch (IOException e) {
			e.printStackTrace();
		}
		return filename;
	}

	private void sendErrorMessage(String errcode, String errormessage) {
		out.println("HTTP/1.1 " + errcode + " " + errormessage);
		out.println("content-type:text/html");
		out.println("<html>");
		out.println();
		out.println("<title>");
		out.println("ErrorMessage");
		out.println("</title>");
		out.println("<body>");
		out.println("<h1>ErrorCode:" + errcode + " ErrorMessage:"
				+ errormessage + "</h1>");
		out.println("</body>");
		out.println("</html>");
		out.flush();
		out.close();
		try {
			in.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private void sendFileinfor(String filename) {
		File file = new File(Processor.WEB_ROOT + filename);
		if (!file.exists()) {
			sendErrorMessage("404", "file not found");
			return;
		}
		byte[] content = new byte[(int) file.length()];
		try {
			InputStream in = new FileInputStream(file);
			in.read(content);
			out.println("HTTP/1.1 200 queryfile");
			out.println("content-length:" + content.length);
			out.println();
			out.write(content);
			out.flush();
			out.close();
			in.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			sendErrorMessage("404", "file not found");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
